import classnames from 'classnames'
import { useNavigate } from 'react-router-dom'
import { NavBar, SearchBar, Dialog } from 'antd-mobile'
import { useAppDispatch, useAppSelector } from '@/store/index'
import Icon from '@/components/icon/index'
import styles from './index.module.scss'
import { useState } from 'react'
// import { useDebounce } from '@/hooks/useDebounce'
import { useDebounceFn } from 'ahooks'
import { getSuggestionAsync, setHistories, clearHistories, delHistory } from '@/store/index'

const SearchPage = () => {
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const [keyword, setKeyword] = useState('')
  const { suggestion, histories } = useAppSelector((state) => state.searchSlice)
  //1-1, 使用自定义防抖函数包裹
  // const setKeywordDebounce = useDebounce<string>((e) => {
  //   setKeyword(e as string)
  // }, 1000)
  //2-1, 使用ahooks防抖函数包裹
  const { run } = useDebounceFn(
    (e) => {
      dispatch(getSuggestionAsync({ q: e }))
    },
    { wait: 500 }
  )
  function onChange(e: string) {
    //1-2,使用自定义防抖包裹后的函数
    // setKeywordDebounce(e)
    // 2-2，使用ahooks包裹后的函数
    setKeyword(e)
    run(e)
  }
  // 高亮匹配字符串
  function highLight(str: string) {
    const exp = new RegExp(keyword, 'gi')
    return str.replace(exp, (match) => {
      return `<span>${match}</span>`
    })
  }
  // 搜索事件
  function onSearch(keyword: string) {
    if (!keyword) return
    dispatch(setHistories(keyword))
    // navigate('/search/result?key=' + keyword)
    navigate({
      pathname: '/search/result',
      search: '?key=' + keyword
    })
  }
  // 清空历史记录
  function onClickHistory() {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要清空记录吗？',
      onConfirm: function () {
        dispatch(clearHistories())
      }
    })
  }
  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => navigate(-1)}
        right={
          <span className="search-text" onClick={() => onSearch(keyword)}>
            搜索
          </span>
        }
      >
        <SearchBar placeholder="请输入关键字搜索" value={keyword} onChange={onChange} />
      </NavBar>

      {!keyword && (
        <div
          className="history"
          style={{
            display: keyword ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={onClickHistory}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {histories.map((item, index) => (
              <span key={index} className="history-item">
                <span className="text-overflow" onClick={() => onSearch(item)}>
                  {item}
                </span>
                <Icon type="iconbtn_essay_close" onClick={() => dispatch(delHistory(item))} />
              </span>
            ))}
          </div>
        </div>
      )}

      <div className={classnames('search-result', keyword ? 'show' : '')}>
        {!!suggestion.length &&
          suggestion[0] &&
          suggestion.map((item, index) => (
            <div className="result-item" key={index} onClick={() => onSearch(item)}>
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value text-overflow"
                dangerouslySetInnerHTML={{ __html: highLight(item) }}
              ></div>
            </div>
          ))}
      </div>
    </div>
  )
}

export default SearchPage
